from enum import Enum, auto
from typing import Optional, Dict, Any
import logging
import re

class UnlockErrorType(Enum):
    """解锁错误类型枚举"""
    SUCCESS = auto()                 # 成功
    DEVICE_UNPAID = auto()           # 设备欠费
    DEVICE_NOT_ACTIVE = auto()       # 设备未满60天
    NOT_ATT_DEVICE = auto()          # 非AT&T设备
    TOO_MANY_REQUESTS = auto()       # 请求次数过多
    DUPLICATE_REQUEST = auto()        # 重复请求
    TECHNICAL_ISSUE = auto()         # 技术问题
    DEVICE_BLACKLISTED = auto()      # 设备在黑名单
    ACCOUNT_CONFLICT = auto()        # 账户冲突
    DEVICE_RESTRICTED = auto()       # 设备限制30天
    DEVICE_INACTIVE = auto()         # 设备不活跃
    UNKNOWN = auto()                 # 未知错误

class ErrorHandler:
    def __init__(self):
        """初始化错误处理器"""
        self.logger = logging.getLogger(__name__)
        self._error_patterns = self._init_error_patterns()
        self._error_messages = self._init_error_messages()

    def _init_error_patterns(self) -> Dict[UnlockErrorType, str]:
        """初始化错误匹配模式"""
        return {
            UnlockErrorType.DEVICE_UNPAID: r"device.+past[\s-]?due|outstanding[\s-]?balance|unpaid",
            UnlockErrorType.DEVICE_NOT_ACTIVE: r"60[\s-]?days|activation[\s-]?period|wait.*activate",
            UnlockErrorType.NOT_ATT_DEVICE: r"not.*AT&?T|different[\s-]?carrier|another[\s-]?carrier",
            UnlockErrorType.TOO_MANY_REQUESTS: r"too[\s-]?many.*requests|24[\s-]?hours|try[\s-]?again[\s-]?later",
            UnlockErrorType.DUPLICATE_REQUEST: r"already.*submitted|duplicate.*request|pending.*request",
            UnlockErrorType.TECHNICAL_ISSUE: r"technical[\s-]?issue|system[\s-]?error|try[\s-]?again",
            UnlockErrorType.DEVICE_BLACKLISTED: r"blacklisted|reported.*lost|reported.*stolen",
            UnlockErrorType.ACCOUNT_CONFLICT: r"active.*another.*account|different.*account",
            UnlockErrorType.DEVICE_RESTRICTED: r"30[\s-]?day.*restriction|restricted.*30[\s-]?days",
            UnlockErrorType.DEVICE_INACTIVE: r"inactive.*status|not.*active.*service",
            UnlockErrorType.SUCCESS: r"confirmation.*email|unlock.*successful|request.*submitted"
        }

    def _init_error_messages(self) -> Dict[UnlockErrorType, str]:
        """初始化错误消息"""
        return {
            UnlockErrorType.DEVICE_UNPAID: "设备存在欠费，请清除欠费后重试",
            UnlockErrorType.DEVICE_NOT_ACTIVE: "设备激活时间未满60天，请等待激活期满后重试",
            UnlockErrorType.NOT_ATT_DEVICE: "该设备不是AT&T运营商的设备",
            UnlockErrorType.TOO_MANY_REQUESTS: "24小时内提交的请求次数过多，请稍后重试",
            UnlockErrorType.DUPLICATE_REQUEST: "该设备已存在解锁申请，请勿重复提交",
            UnlockErrorType.TECHNICAL_ISSUE: "系统出现技术问题，请稍后重试",
            UnlockErrorType.DEVICE_BLACKLISTED: "该设备在黑名单中，无法解锁",
            UnlockErrorType.ACCOUNT_CONFLICT: "该设备在其他账户中处于活跃状态",
            UnlockErrorType.DEVICE_RESTRICTED: "该设备已被限制30天",
            UnlockErrorType.DEVICE_INACTIVE: "该设备处于不活跃状态",
            UnlockErrorType.SUCCESS: "解锁请求提交成功",
            UnlockErrorType.UNKNOWN: "未知错误，请检查日志获取详细信息"
        }

    def analyze_error(self, error_text: str) -> Dict[str, Any]:
        """
        分析错误文本并返回错误类型和消息
        :param error_text: 错误文本
        :return: 包含错误类型和消息的字典
        """
        try:
            # 转换为小写进行匹配
            error_text = error_text.lower()
            
            # 遍历所有错误模式进行匹配
            for error_type, pattern in self._error_patterns.items():
                if re.search(pattern, error_text, re.IGNORECASE):
                    return {
                        "type": error_type,
                        "message": self._error_messages[error_type],
                        "original_text": error_text
                    }
            
            # 如果没有匹配到任何模式，返回未知错误
            return {
                "type": UnlockErrorType.UNKNOWN,
                "message": self._error_messages[UnlockErrorType.UNKNOWN],
                "original_text": error_text
            }
            
        except Exception as e:
            self.logger.error(f"分析错误文本时出现异常: {str(e)}")
            return {
                "type": UnlockErrorType.UNKNOWN,
                "message": f"错误分析失败: {str(e)}",
                "original_text": error_text
            }

    def get_error_message(self, error_type: UnlockErrorType) -> str:
        """
        获取指定错误类型的消息
        :param error_type: 错误类型
        :return: 错误消息
        """
        return self._error_messages.get(error_type, self._error_messages[UnlockErrorType.UNKNOWN])

    def is_success(self, error_type: UnlockErrorType) -> bool:
        """
        检查是否为成功状态
        :param error_type: 错误类型
        :return: 是否成功
        """
        return error_type == UnlockErrorType.SUCCESS

    def is_retriable(self, error_type: UnlockErrorType) -> bool:
        """
        检查错误是否可以重试
        :param error_type: 错误类型
        :return: 是否可以重试
        """
        retriable_errors = {
            UnlockErrorType.TECHNICAL_ISSUE,
            UnlockErrorType.TOO_MANY_REQUESTS
        }
        return error_type in retriable_errors

    def should_skip(self, error_type: UnlockErrorType) -> bool:
        """
        检查是否应该跳过当前设备
        :param error_type: 错误类型
        :return: 是否应该跳过
        """
        skip_errors = {
            UnlockErrorType.NOT_ATT_DEVICE,
            UnlockErrorType.DEVICE_BLACKLISTED,
            UnlockErrorType.DEVICE_UNPAID,
            UnlockErrorType.DEVICE_NOT_ACTIVE,
            UnlockErrorType.ACCOUNT_CONFLICT,
            UnlockErrorType.DEVICE_RESTRICTED,
            UnlockErrorType.DEVICE_INACTIVE
        }
        return error_type in skip_errors 